package com.x.springboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import com.x.springboot.dto.AdminUserDetails;
import com.x.springboot.dto.UserDTO;
import com.x.springboot.exception.Asserts;
import com.x.springboot.model.User;
import com.x.springboot.mapper.UserMapper;
import com.x.springboot.service.UserCacheService;
import com.x.springboot.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.x.springboot.util.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author x.li
 * @since 2021-06-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService,UserDetailsService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserCacheService userCacheService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(User user) {
        userMapper.insert(user);
    }

    @Override
    public void delete(Integer id) {
        removeById(id);
    }

    @Override
    public void deleteBatch(List<Integer> ids) {
        removeByIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(User user) {
        userMapper.updateById(user);
    }

    @Override
    public User get(Long id) {
        User user = getById(id);
        return user;
    }

    @Override
    public PageInfo<User> query(User user,int pageNum,int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<User> userList = userMapper.query(user);
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        return pageInfo;
    }

    @Override
    public User register(UserDTO umsAdminParam) {
        User umsAdmin = new User();
        BeanUtils.copyProperties(umsAdminParam, umsAdmin);
        umsAdmin.setIsDelete(0);
        //查询是否有相同用户名的用户
        //将密码进行加密操作
        String encodePassword = SecureUtil.md5(umsAdmin.getPassword());
        umsAdmin.setPassword(encodePassword);
        userMapper.insert(umsAdmin);
        return umsAdmin;
    }

    @Override
    public String login(String username, String password) {
        String token = null;
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = loadUserByUsername(username);
            String encodePassword = SecureUtil.md5(password);
            if(!encodePassword.equals(userDetails.getPassword())){
                Asserts.fail("密码不正确");
            }
            if(!userDetails.isEnabled()){
                Asserts.fail("帐号已被禁用");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }




    @Override
    public String refreshToken(String oldToken) {
        return jwtTokenUtil.refreshHeadToken(oldToken);
    }

    @Override
    public User getAdminByUsername(String username) {
        User admin = BeanUtil.toBean(userCacheService.getAdmin(username), User.class);
        if(admin!=null && admin.getId() != null && admin.getIsDelete() == 0) {
            return  admin;
        }
        List<User> adminList = userMapper.queryAllByName(username);
        if (adminList != null && adminList.size() > 0) {
            admin = adminList.get(0);
            userCacheService.setAdmin(admin);
            return admin;
        }
        return null;
    }

    @Override
    public UserDetails loadUserByUsername(String username){
        //获取用户信息
        User admin = getAdminByUsername(username);
        if (admin != null) {
            return new AdminUserDetails(admin);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }
}
